package com.custom.base.util

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import com.custom.base.manager.SDActivityManager
import kotlin.collections.ArrayList

/**
 * 作者：.
 * 时间：2017/3/7.
 * 说明：
 */
class PermissionUtil {
    /**
     * 判断当前为M以上版本
     * author LH
     * data 2016/7/27 11:29
     */
    private val isOverMarshmallow: Boolean
        private get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M

    /**
     * 获得没有授权的权限
     * author LH
     * data 2016/7/27 11:46
     */
    private fun findDeniedPermissions(
        activity: Activity,
        permissions: List<String>?
    ): List<String> {
        val denyPermissions: MutableList<String> = ArrayList()
        for (value in permissions!!) {
            if (activity.checkSelfPermission(value) != PackageManager.PERMISSION_GRANTED) {
                denyPermissions.add(value)
            }
        }
        return denyPermissions
    }

    /**
     * 获取所有权限
     * author LH
     * data 2016/7/27 13:37
     */
    fun requestPermissions(
        p: List<String>,
        requestCode: Int,
        isOverMarshmallow: OnIsOverMarshmallow? = null
    ) {
        val activity = SDActivityManager.instance.lastActivity
        val permissions = activity?.let { findDeniedPermissions(it, p) }
        if (permissions != null) {
            if (permissions.isNotEmpty()) {
                activity.requestPermissions(permissions.toTypedArray(), requestCode)
            }else{
                isOverMarshmallow?.noIsOverMarshmallow()
            }
        }
    }

    /**
     * 获取相机权限
     */
    fun requestCamera(requestCode: Int,isOverMarshmallow: OnIsOverMarshmallow? = null){
        requestPermissions(listOf(
            Manifest.permission.CAMERA
        ),requestCode,isOverMarshmallow)
    }
    /**
     * 获取存储权限
     */
    fun requestStorage(requestCode: Int,isOverMarshmallow: OnIsOverMarshmallow? = null){
        requestPermissions(listOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ),requestCode,isOverMarshmallow)
    }

    /**
     * 手机是否开启位置服务，如果没有开启那么所有app将不能使用定位功能
     */
    fun isLocServiceEnable(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        val network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        return gps || network
    }

    interface OnIsOverMarshmallow {
        fun noIsOverMarshmallow()
    }
}